import React, { Component } from 'react';
import DocumentTitle from 'react-document-title';
import { Link, Redirect } from "react-router-dom";
import { connect } from 'react-redux';
import Routes from './routes';
import { breadcrumbNameMap } from './routes/config';
import SiderCustom from './components/SiderCustom';
import HeaderCustom from './components/HeaderCustom';
import { Layout, Breadcrumb, Icon } from 'antd';
import http from './utils/http';
import { USER_SERVICE } from './utils/http/config';
import { setUser, setScreen } from './action';


class App extends Component {
  constructor(props) {
    super(props);
    this.state = {
      collapsed: false,
      title: '',
      extraBreadcrumbItems: []
    };
  }
  
  componentDidMount() {
    const userId = localStorage.getItem('__rs');
    if (userId) {
      this.getClientWidth();
      window.onresize = () => {
        // console.log('屏幕变化了');
        this.getClientWidth();
      }
      const { history, dispatch } = this.props;
      http.get(`${USER_SERVICE}/${userId}`).then(response => {
        dispatch(setUser(response.data));
      }, () => {
        localStorage.removeItem('__rs');
        localStorage.removeItem('__rstk');
        history.push('/login');
      });
    }
  }
  // 获取当前浏览器宽度并设置responsive管理响应式
  getClientWidth() { 
    const clientWidth = window.innerWidth;
    // console.log(`屏幕大小：${clientWidth}`);
    this.props.dispatch(setScreen({ isMobile: clientWidth <= 992 }));
  };

  getBreadcrumbMap(item) {
    let extraBreadcrumbItems = [];
    if (item.key === '/app/dashboard/index') {
      extraBreadcrumbItems.push(<Breadcrumb.Item key="/"><Icon type="dashboard" /><span>首页</span></Breadcrumb.Item>);
    } else {
      const pathSnippets = item.key.split('/').filter(i => i);
      extraBreadcrumbItems = pathSnippets.map((_, index) => {
        const url = `/${pathSnippets.slice(0, index + 1).join('/')}`;
        if(url === '/app') {
          return <Breadcrumb.Item key={url}><Link to="/"><Icon type="dashboard" /><span>首页</span></Link></Breadcrumb.Item>;
        } else if (index > 1 && index < pathSnippets.length - 1) {
          return <Breadcrumb.Item key={url}><Link to={url}>{breadcrumbNameMap[url]?.icon ? <Icon type={breadcrumbNameMap[url].icon} /> : ''}<span>{breadcrumbNameMap[url]?.title}</span></Link></Breadcrumb.Item>;
        } else {
          return <Breadcrumb.Item key={url}>{breadcrumbNameMap[url]?.icon ? <Icon type={breadcrumbNameMap[url].icon} /> : ''}<span>{breadcrumbNameMap[url]?.title}</span></Breadcrumb.Item>;
        }
      });
    }
    return extraBreadcrumbItems;
  }

  setTitle(item) {
    if (this.state.title !== item.title) {
      this.setState({
        title: item.title,
        extraBreadcrumbItems: this.getBreadcrumbMap(item)
      });
    }
  }
  render() {
    const { collapsed, title, extraBreadcrumbItems } = this.state;
    const { screen, user } = this.props;
    const userId = localStorage.getItem('__rs');
    if (userId) {
      return (
        <DocumentTitle title={title}>
          <Layout hasSider={false}>
            <HeaderCustom toggle={() => {this.setState({ collapsed: !collapsed })}} collapsed={collapsed} />
            <Layout>
              {!screen.isMobile && <SiderCustom collapsed={collapsed} user={user} />}
              <Layout className="rs-content">
                <Layout.Content>
                  <div className="breadCrumb-block">
                    <Breadcrumb>{extraBreadcrumbItems}</Breadcrumb>
                  </div>
                  <Routes fnRouterChange={this.setTitle.bind(this)} />
                </Layout.Content>
                <Layout.Footer style={{ textAlign: 'center' }}>
                  CCAPP-Admin © {new Date().getFullYear()}
                </Layout.Footer>
              </Layout>
            </Layout>
          </Layout>
        </DocumentTitle>
      );
    } else {
      return <Redirect to="/login" />
    }
  }
}

export default connect(state => ({
  screen: state.screen,
  user: state.user
}))(App);
